//
//  UIImageView+Remote.swift
//  SitPosition
//
//  Created by apple on 2019/2/9.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit


/**
 * 七牛网络加载逻辑
 */
extension UIImageView {
    
    func qiniu_setImage(_ url: URL?, placeholder: UIImage?, maxSize: CGFloat, animated: Bool = false) {
        guard let url_ = url else {
            image = nil
            return
        }
        image = placeholder
        
        guard var urlComponents: URLComponents = URLComponents(url: url_, resolvingAgainstBaseURL: false) else {
            image = nil
            return
        }
        urlComponents.path = urlComponents.path.appendingFormat("?imageView2/2/w/%d", Int(maxSize))
        let qiniuURL: URL? = urlComponents.url
        sd_setImage(with: qiniuURL, placeholderImage: placeholder, options: .scaleDownLargeImages) { (image, error, type, url) in
            DispatchQueue.main.async { [weak self] in
                guard let image_ = image else {
                    return
                }
                self?.image = image_
                
                guard animated else { return }
                let animationKey: String = "fadeAnimation"
                self?.layer.removeAnimation(forKey: animationKey)
                
                let transition: CATransition = CATransition()
                transition.duration = 1.0
                transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
                transition.type = CATransitionType.fade
                self?.layer.add(transition, forKey: animationKey)
            }
        }
    }
}
